<?php
namespace App\Libs\Remote;
/**
 *  远程调用访问类
 */
class Client
{
    protected $handler;
    static $defaultApiConf = array(
        'method' => 'GET',
        'connect_timeout' => 2,
        'timeout' => 2,
    );
    public static function build($service, $api, $params) {
        $config = \App\Libs\Base\Config::instance()->remote;
        if ( ! isset($config[$service])) {
            return FALSE;
        }
        $host = $config[$service]['host'];
        $apis = $config[$service]['api'];
        $apiConf = self::getConfig($apis, $api);
        $url = $host . $api;

        $ch = curl_init();
        if ($apiConf['method'] === 'GET') {
            $url .= '?' . http_build_query($params);
            curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_POST, TRUE);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $apiConf['connect_timeout']);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //
        curl_setopt($ch, CURLOPT_TIMEOUT, $apiConf['timeout']);

        return new self($ch);
    }

    protected static function getConfig($apis, $api) {
        $apiConf = array();
        if (isset($apis[$api])) {
            $apiConf = $apis[$api];
        }
        return array_merge(self::$defaultApiConf, $apiConf);
    }


    private function __construct($ch) {
        $this->handler = $ch;
    }

    public function execute() {
        $response = curl_exec($this->handler);
        $error = curl_error($this->handler);
        $header_size = curl_getinfo($this->handler, CURLINFO_HEADER_SIZE);
        $result = array('curl_error' => NULL);
        if ( ! empty($error)) {
            $result['curl_error'] = $error;
            return $result;
        }
        $result['header'] = substr($response, 0, $header_size);
        $result['body'] = substr( $response, $header_size );
        $result['http_code'] = curl_getinfo($this->handler, CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($this->handler, CURLINFO_EFFECTIVE_URL);
        curl_close($this->handler);
        return $result;
    }
}
